package com.qf.conterller;

import com.qf.pojo.User;
import com.qf.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//conterller层处理请求并将数据发送到service层
@WebServlet(name = "UserServlet",urlPatterns = "/login")
public class UserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //获取请求中的数据并使用BeanUtils工具封装成User对象
            User user = new User();
            BeanUtils.populate(user,req.getParameterMap());
            //将User对象传到Service层进行业务逻辑处理
            UserServiceImpl userService = new UserServiceImpl();
            User existUser = userService.login(user);
            if (existUser!=null){
                //登录成功，跳转到首页并将信息存储到Session域
                req.getSession().setAttribute("msg",existUser);
                resp.sendRedirect(req.getContextPath()+"/index.jsp");
                return;
            } else {
                //登录失败就将失败信息储存到请求域并转发到登录页面
                req.setAttribute("errMsg","用户名或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("errMsg","登录失败");
        }
        //登录失败就跳转回登录页面
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
